<?php
/**
 * @file
 */
/**
 * Page callback: Generates the appropriate wordgame word administration form.
 *
 * This function generates the wordgame_word registration, multiple wordgame_word cancellation,
 * or filtered wordgame_word list admin form, depending on the argument and the POST
 * form values.
 *
 * @param string $callback_arg
 *   (optional) Indicates which form to build. Defaults to '', which will
 *   trigger the wordgame_word filter form. If the POST value 'op' is present, this
 *   function uses that value as the callback argument.
 *
 * @return string
 *   A renderable form array for the respective request.
 */
function wordgame_word_admin($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;

  switch ($op) {
    case t('Add new word'):
    case 'create':
      module_load_include('inc', 'wordgame_word', 'wordgame_word.form');
      $build['wordgame_word_edit'] = drupal_get_form('wordgame_word_edit');
      break;
    default:
      if (!empty($_POST['words']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
        $build['wordgame_word_multiple_delete_confirm'] = drupal_get_form('wordgame_word_multiple_delete_confirm');
      }
      else {
        $build['wordgame_word_filter_form'] = drupal_get_form('wordgame_word_filter_form');
        $build['wordgame_word_words'] = drupal_get_form('wordgame_word_words');
      }
  }
  return $build;
}

/**
 * Form builder; User administration page.
 *
 * @ingroup forms
 * @see wordgame_word_admin_wordgame_word_validate()
 * @see wordgame_word_admin_wordgame_word_submit()
 */
function wordgame_word_words() {
  $header = array(
    'word' => array('data' => t('Word'), 'field' => 'c.word'),
    'status' => array('data' => t('Status'), 'field' => 'c.status'),
    'length' => array('data' => t('Length'), 'field' => 'c.length'),
    'tid' => array('data' => t('Categories')),
    'modified' => array('data' => t('Modified'), 'field' => 'c.modified'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('wordgame_word', 'c');
  $query->leftJoin('field_data_word_tid', 't', "c.wid = t.entity_id");
  wordgame_word_build_filter_query($query);

  $count_query = clone $query;
  $count_query->addExpression('COUNT(c.wid)');

  $query->addField('t', 'word_tid_tid', 'tid');
  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('c', array('wid', 'word', 'status', 'length', 'modified'))
    ->limit(50)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
  );
  $options = array();
  foreach (module_invoke_all('wordgame_word_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'unblock',
  );
  $options = array();
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  $destination = drupal_get_destination();

  $terms = wordgame_word_categories_options();

  foreach ($result as $word) {
    $options[$word->wid] = array(
      'word' => $word->word,//l($word->word, "wordgame_word/$word->wid", array('attributes' => array('target' => '_blank'))),
      'status' =>  $word->status ?  t('Yes') : t('No'),
      'length' => $word->length,
      'tid' => !empty($word->tid) ? $terms[$word->tid] : '',
      'modified' => date('d-m-Y H:i', $word->modified),
      'operations' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => t('edit'),
          '#href' => "admin/wordgame/words/edit/{$word->wid}",
          '#options' => array('query' => $destination)
        )
      ),
    );
  }

  $form['words'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No people available.'),
  );
  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

/**
 * Submit the user administration update form.
 */
function wordgame_word_words_submit($form, &$form_state) {
  $operations = module_invoke_all('wordgame_word_operations', $form, $form_state);
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked accounts.
  $accounts = array_filter($form_state['values']['words']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($accounts), $operation['callback arguments']);
    }
    else {
      $args = array($accounts);
    }
    call_user_func_array($function, $args);

    drupal_set_message(t('The update has been performed.'));
  }
}

function wordgame_word_words_validate($form, &$form_state) {
  $form_state['values']['words'] = array_filter($form_state['values']['words']);
  if (count($form_state['values']['words']) == 0) {
    form_set_error('', t('No words selected.'));
  }
}

/**
 * Extends a query object for wordgame_word administration filters based on session.
 *
 * @param $query
 *   Query object that should be filtered.
 */
function wordgame_word_build_filter_query(SelectQuery $query) {
  // Extend Query with filter conditions.
  $filters = isset($_SESSION['wordgame_word_overview_filter']) ? $_SESSION['wordgame_word_overview_filter'] : array();
  foreach ($filters as $key => $value) {
    if ($key === 'word') {
      if (!empty($value)) {
        $query->condition($key, "%%{$value}%%", 'LIKE');
      }
    }
    if ($key === 'word_tid_tid') {
      $value = array_filter($value);
      if (!empty($value)) {
        $query->condition($key, $value, 'IN');
      }
    }
    else {
      if ($value != "") {
        $query->condition($key, $value);
      }
    }
  }
}

/**
 * Form builder; Return form for user administration filters.
 *
 * @ingroup forms
 * @see wordgame_word_filter_form_submit()
 */
function wordgame_word_filter_form() {
  $session = isset($_SESSION['wordgame_word_overview_filter']) ? $_SESSION['wordgame_word_overview_filter'] : array();
  $i = 0;
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only words where'),
    '#theme' => 'exposed_filters__wordgame_word',
    '#tree' => TRUE
  );
  $options = array('' => t('Choose status')) + array('0' => t('Inactive'), 1 => t('Active'));
  $form['filters']['status'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Status'),
    '#default_value' => isset($session['status']) ? $session['status'] : '',
  );
  $form['filters']['word'] = array(
    '#type' => 'textfield',
    '#title' => t('Word'),
    '#default_value' => isset($session['word']) ? $session['word'] : '',
    '#size' => 20
  );
  $form['filters']['word_tid_tid'] = array(
    '#type' => 'select',
    '#title' => t('Catalogue'),
    '#default_value' => isset($session['word_tid_tid']) ? $session['word_tid_tid'] : '',
    '#size' => 5,
    '#multiple' => TRUE,
    '#options' => array('' => t('Choose catalogue')) + wordgame_word_categories_options()
  );

  $form['filters']['actions'] = array(
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['filters']['actions']['filter'] = array(
    '#type' => 'submit',
    '#value' =>  t('Filter'),
  );
  if (count($session)) {
    $form['filters']['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Reset'),
    );
  }
  return $form;
}

/**
 * Process result from user administration filter form.
 */
function wordgame_word_filter_form_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  switch ($op) {
    case t('Filter'):
      // Apply every filter that has a choice selected other than 'any'.
      if (isset($form_state['values']['filters'])) {
        unset($form_state['values']['filters']['actions']);
        $_SESSION['wordgame_word_overview_filter'] = $form_state['values']['filters'];
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['wordgame_word_overview_filter']);
      break;
    case t('Reset'):
      $_SESSION['wordgame_word_overview_filter'] = array();
      break;
    case t('Update'):
      return;
  }

  $form_state['redirect'] = 'admin/wordgame/words';
  return;
}

function wordgame_word_multiple_delete_confirm($form, &$form_state) {
  $edit = $form_state['input'];

  $form['words'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  $words = wordgame_word_load_multiple(array_keys(array_filter($edit['words'])));
  foreach ($words as $wid => $word) {
    $form['words'][$wid] = array(
      '#type' => 'hidden',
      '#value' => $wid,
      '#prefix' => '<li>',
      '#suffix' => check_plain($word->word) . "</li>\n",
    );
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  return confirm_form($form,
    t('Are you sure you want to cancel these words?'),
    'admin/wordgame/words', t('This action cannot be undone.'),
    t('Delete words'), t('Cancel'));
}

/**
 * Submit handler for mass-word delete form.
 */
function wordgame_word_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    foreach ($form_state['values']['words'] as $wid => $value) {
      wordgame_word_delete_word($wid, 'wordgame_word_delete_word');
    }
  }
  $form_state['redirect'] = 'admin/wordgame/words';
}

/**
 * Menu callback function
 */
function wordgame_word_setting($form, &$form_state) {
  $form['wordgame_word_index'] = array(
    '#type' => 'textfield',
    '#title' => t('Path to index file'),
    '#required' => TRUE,
    '#default_value' => variable_get('wordgame_word_index', drupal_get_path('module', 'wordgame_word') . "/data/wordgame_word.index")
  );
  $form['wordgame_word_dict'] = array(
    '#type' => 'textfield',
    '#title' => t('Path to dict file'),
    '#required' => TRUE,
    '#default_value' => variable_get('wordgame_word_dict', drupal_get_path('module', 'wordgame_word') . "/data/wordgame_word.dict")
  );
  return system_settings_form($form);
}

function wordgame_word_import($form, $form_state) {
  $words = wordgame_word_load_words();
  $form['total'] = array(
    '#type' => 'item',
    '#title' => t('Total words'),
    '#markup' => count($words)
  );
  $form['import'] = array(
    '#type' => 'fieldset',
    '#title' => t('Import'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $imported_words = variable_get('wordgame_word_imported_words', array());
  $form['import']['status'] = array(
    '#title' => t("Status"),
    '#type' => 'item',
    '#markup' => t('@num_wid words imported.', array('@num_wid' => count($imported_words)))
  );
  $form['import']['wordgame_word_import_limit'] = array(
    '#type' => 'textfield',
    '#title' => t('Import limit'),
    '#required' => TRUE,
    '#default_value' => variable_get('wordgame_word_import_limit', 100)
  );
  $form['import']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import dictionary'),
    '#submit' => array('wordgame_word_import_form_submit'),
  );
  $form['import']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Clear all results'),
    '#submit' => array('wordgame_word_reset_form_submit'),
  );

  return $form;
}

/**
 * FormAPI submission to import words.
 */
function wordgame_word_import_form_submit($form_id, &$form_state) {
  variable_set('wordgame_word_import_limit', $form_state['values']['wordgame_word_import_limit']);
  module_load_include('inc', 'wordgame_word', 'wordgame_word_import_batch');
  wordgame_word_import_words_batch($form_state);
}

function wordgame_word_reset_form_submit($form, &$form_state) {
  db_query('TRUNCATE TABLE {wordgame_word}');
  variable_del('wordgame_word_imported_words');
  drupal_set_message(t('Clear all results successful'));
}